<template>
  <PageContainer>
    <Header title="选择附件" :default-slot-content-height="160">
      <view class="hb-text-xs hb-text-[#E29942] hb-py-2.5 hb-px-4 hb-bg-[#FFF4E7]">
        仅支持从知识库选择文件，如需添加新文件，请先
        <text @click="handleKnowledgeBase" class="hb-text-[#2878FF]">前往知识库</text>
        上传。
        <view class="hb-mt-3">当前文件列表不显示已关联的文件；</view>
      </view>
    </Header>
    <view class="hb-p-4 hb-pb-[200rpx]">
      <!-- 这个区域加分页 -->
      <Paglist
        v-model="fileList"
        :is-init-api="false"
        :is-show-loadmore="false"
        @register="register"
      >
        <view
          v-if="fileList.length > 0"
          class="hb-box-shadow-base hb-rounded-xl hb-p-4 hb-bg-white"
        >
          <template v-for="item in fileList" :key="item.id">
            <view
              class="hb-flex hb-items-center hb-py-4 hb-border-solid hb-border-[#EBEDF0] hb-border-b"
            >
              <TmIcon
                v-if="!isSelected(item.id)"
                class="hb-flex-shrink-0 hb-mr-2"
                name="ali-icon icon-duoxuan_weixuanzhong"
                :follow-theme="false"
                :font-size="48"
                @click="toggleSelect(item)"
              />
              <TmIcon
                v-else
                class="hb-flex-shrink-0 hb-mr-2"
                name="ali-icon icon-duoxuan_xuanzhong"
                :follow-theme="false"
                color="#2878FF"
                :font-size="48"
                @click="toggleSelect(item)"
              />
              <TmIcon
                class="hb-flex-shrink-0"
                :name="`ali-icon ${getFileIcon(item.fileSuffix).icon}`"
                :follow-theme="false"
                :color="getFileIcon(item.fileSuffix).color"
                :font-size="80"
                @click="toggleSelect(item)"
              />
              <view
                @click="toggleSelect(item)"
                class="hb-ml-2 hb-flex-1 hb-flex hb-flex-col hb-justify-between"
              >
                <text class="text-overflow-1 hb-font-bold hb-text-sm">{{ item.fileName }}</text>
                <view class="hb-flex hb-items-center hb-mt-1">
                  <TmText
                    :label="fileSizeConversion(item.fileSize)"
                    :font-size="24"
                    color="#969799"
                  />
                  <TmText class="hb-mx-1" label="·" color="#969799" :font-size="24" />
                  <TmText :label="formatToDate(item.createTime)" :font-size="24" color="#969799" />
                </view>
              </view>
              <TmButton
                class="hb-flex-shrink-0"
                :margin="[0, 0]"
                :padding="[24, 0]"
                :block="true"
                :follow-theme="false"
                :height="48"
                :font-size="24"
                outlined
                :round="16"
                label="查看"
                @click="handleOpenDocument(item)"
              />
            </view>
          </template>
        </view>
      </Paglist>
    </view>

    <!-- 底部确认按钮 -->
    <BottomSubmit
      v-if="selectedIds.length > 0"
      :submit-loading="loading"
      :submitBtnLabel="`确定选择(${selectedIds.length}/${maxSelectCount})`"
      :submitBtnColor="'#2878FF'"
      @submit="handleConfirm"
    />
  </PageContainer>
</template>

<script lang="ts" setup>
  import { KnowledgeBaseFileListResult } from '@/api/knowledgeBase/types';
  import { useConList } from '@/components/Paglist/useConList';
  import { getFileIcon } from '@/utils';
  import { formatToDate } from '@/utils/dateUtil';
  import { fileSizeConversion } from '@/utils/file';
  import { FunctionArgs } from '@vueuse/core';
  import { useUpload } from '@/hooks/file/useUpload';
  import { botAttachmentAddOrUpdate, selectKnowledgeBaseFileList } from '@/api/card';
  const { openDocument } = useUpload();
  /* attachmentDocsChoose 选择附件 */
  let success: FunctionArgs | undefined;
  const maxSelectCount = ref(0);
  customOnload<'attachmentDocsChoose'>((options) => {
    success = options.success;
    maxSelectCount.value = options.maxSelectCount;
    refresh();
  });

  const fileList = ref<KnowledgeBaseFileListResult[]>([]);
  const selectedIds = ref<number[]>([]);
  const loading = ref(false);
  const [register, { refresh }] = useConList();
  provide('api', selectKnowledgeBaseFileList);

  // 判断是否选中
  const isSelected = (id: number) => {
    return selectedIds.value.includes(id);
  };

  // 切换选中状态
  const toggleSelect = (item: KnowledgeBaseFileListResult) => {
    const index = selectedIds.value.indexOf(item.id);
    if (index === -1) {
      // 未选中,尝试选中
      if (selectedIds.value.length >= maxSelectCount.value) {
        uni.showToast({
          title: `最多只能选择${maxSelectCount.value}个文件`,
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      selectedIds.value.push(item.id);
    } else {
      // 已选中,取消选中
      selectedIds.value.splice(index, 1);
    }
  };

  // 确认选择
  const handleConfirm = async () => {
    loading.value = true;
    try {
      await botAttachmentAddOrUpdate(selectedIds.value);
      uni.showToast({
        title: '添加成功',
        icon: 'success',
        duration: 2000,
      });
      success?.();
      setTimeout(() => {
        navigateBack();
      }, 1000);
    } catch (error) {}
  };

  const handleKnowledgeBase = () => {
    navigateTo({
      name: 'knowledgeBase',
    });
  };

  const handleOpenDocument = (item: KnowledgeBaseFileListResult) => {
    openDocument({ filePath: item.filePathUrl, fileType: item.fileSuffix });
  };
</script>
